<template>
  <Layout>
    <div class="min-h-screen bg-gray-50">
      <!-- 预览提示栏 -->
      <div class="bg-yellow-50 border-b border-yellow-200">
        <div class="max-w-4xl mx-auto px-4 py-3 flex justify-between items-center">
          <div class="flex items-center space-x-2">
            <svg class="w-5 h-5 text-yellow-600" fill="currentColor" viewBox="0 0 20 20">
              <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
            </svg>
            <span class="text-yellow-800 font-medium">这是文章预览，尚未发布</span>
          </div>
          <button
            @click="closePreview"
            class="text-yellow-600 hover:text-yellow-800"
          >
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
      </div>

      <!-- 文章内容 -->
      <article class="max-w-4xl mx-auto px-4 py-8">
        <div class="bg-white rounded-lg shadow-md overflow-hidden">
          <!-- 特色图片 -->
          <div v-if="post.featured_image || post.featured_image_preview" class="aspect-w-16 aspect-h-9">
            <img
              :src="post.featured_image_preview || `/storage/${post.featured_image}`"
              :alt="post.title"
              class="w-full h-96 object-cover"
            />
          </div>

          <!-- 文章头部 -->
          <div class="p-8">
            <div class="mb-6">
              <!-- 分类和标签 -->
              <div class="flex items-center space-x-4 mb-4">
                <span v-if="post.category_id" class="text-blue-600 hover:text-blue-800">
                  {{ getCategoryName(post.category_id) }}
                </span>
                <div v-if="post.tags?.length > 0" class="flex flex-wrap gap-2">
                  <span
                    v-for="tag in post.tags"
                    :key="tag"
                    class="px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded"
                  >
                    #{{ tag }}
                  </span>
                </div>
              </div>

              <!-- 标题 -->
              <h1 class="text-4xl font-bold text-gray-900 mb-4">
                {{ post.title }}
              </h1>

              <!-- 文章信息 -->
              <div class="flex items-center space-x-6 text-gray-500">
                <div class="flex items-center space-x-2">
                  <img
                    :src="currentUser.avatar || `https://ui-avatars.com/api/?name=${currentUser.name}&size=100`"
                    :alt="currentUser.name"
                    class="w-10 h-10 rounded-full"
                  />
                  <div>
                    <div class="font-medium text-gray-900">{{ currentUser.name }}</div>
                    <div class="text-sm">@{{ currentUser.username }}</div>
                  </div>
                </div>
                <span>•</span>
                <span>{{ formatDate(new Date()) }}</span>
                <span>•</span>
                <span>预计阅读 {{ readingTime }} 分钟</span>
              </div>
            </div>

            <!-- 摘要 -->
            <div v-if="post.excerpt" class="text-xl text-gray-600 leading-relaxed mb-8">
              {{ post.excerpt }}
            </div>

            <!-- 文章内容 -->
            <div class="prose prose-lg max-w-none" v-html="contentHtml"></div>

            <!-- 文章尾部信息 -->
            <div class="mt-12 pt-8 border-t">
              <!-- SEO信息预览 -->
              <div class="mb-8 p-4 bg-gray-50 rounded-lg">
                <h3 class="font-semibold text-gray-900 mb-3">SEO预览</h3>
                <div class="space-y-2">
                  <div>
                    <span class="text-sm text-gray-500">标题：</span>
                    <span class="text-blue-600">{{ post.meta_title || post.title }}</span>
                  </div>
                  <div>
                    <span class="text-sm text-gray-500">描述：</span>
                    <span class="text-gray-700">{{ post.meta_description || post.excerpt || '暂无描述' }}</span>
                  </div>
                  <div v-if="post.meta_keywords">
                    <span class="text-sm text-gray-500">关键词：</span>
                    <span class="text-gray-700">{{ post.meta_keywords }}</span>
                  </div>
                </div>
              </div>

              <!-- 文章设置预览 -->
              <div class="grid grid-cols-2 gap-4 text-sm">
                <div class="p-3 bg-gray-50 rounded">
                  <span class="text-gray-500">状态：</span>
                  <span class="font-medium">{{ getStatusText(post.status) }}</span>
                </div>
                <div class="p-3 bg-gray-50 rounded">
                  <span class="text-gray-500">访问权限：</span>
                  <span class="font-medium">{{ getAccessLevelText(post.access_level) }}</span>
                </div>
                <div class="p-3 bg-gray-50 rounded">
                  <span class="text-gray-500">允许评论：</span>
                  <span class="font-medium">{{ post.allow_comments ? '是' : '否' }}</span>
                </div>
                <div class="p-3 bg-gray-50 rounded">
                  <span class="text-gray-500">精选文章：</span>
                  <span class="font-medium">{{ post.is_featured ? '是' : '否' }}</span>
                </div>
                <div class="p-3 bg-gray-50 rounded">
                  <span class="text-gray-500">置顶文章：</span>
                  <span class="font-medium">{{ post.is_sticky ? '是' : '否' }}</span>
                </div>
                <div v-if="post.published_at" class="p-3 bg-gray-50 rounded">
                  <span class="text-gray-500">定时发布：</span>
                  <span class="font-medium">{{ formatDateTime(post.published_at) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="mt-6 flex justify-center space-x-4">
          <button
            @click="goBack"
            class="px-6 py-3 bg-white text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50 font-medium"
          >
            返回编辑
          </button>
          <button
            @click="publish"
            v-if="post.status === 'draft'"
            class="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-medium"
          >
            立即发布
          </button>
        </div>
      </article>
    </div>
  </Layout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { usePage } from '@inertiajs/inertia-vue3'
import Layout from '@/Components/Layout.vue'
import { marked } from 'marked'

const page = usePage()
const currentUser = computed(() => page.props.auth?.user || {})

const post = ref({
  title: '',
  slug: '',
  excerpt: '',
  content: '',
  category_id: null,
  tags: [],
  featured_image: null,
  featured_image_preview: null,
  status: 'draft',
  access_level: 'public',
  allow_comments: true,
  is_featured: false,
  is_sticky: false,
  published_at: null,
  meta_title: '',
  meta_description: '',
  meta_keywords: ''
})

const categories = ref([])

// 计算阅读时间
const readingTime = computed(() => {
  const wordsPerMinute = 200
  const wordCount = (post.value.content || '').split(/\s+/).length
  return Math.ceil(wordCount / wordsPerMinute)
})

// 转换Markdown为HTML
const contentHtml = computed(() => {
  return marked(post.value.content || '')
})

const getCategoryName = (categoryId) => {
  const category = categories.value.find(c => c.id === categoryId)
  return category?.name || '未分类'
}

const getStatusText = (status) => {
  const statusMap = {
    draft: '草稿',
    published: '已发布',
    scheduled: '定时发布',
    archived: '已归档'
  }
  return statusMap[status] || status
}

const getAccessLevelText = (level) => {
  const levelMap = {
    public: '公开',
    login_required: '需要登录',
    followers_only: '仅关注者',
    private: '私密'
  }
  return levelMap[level] || level
}

const formatDate = (date) => {
  const d = new Date(date)
  const months = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
  return `${d.getFullYear()}年${months[d.getMonth()]}${d.getDate()}日`
}

const formatDateTime = (datetime) => {
  const d = new Date(datetime)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

const closePreview = () => {
  window.close()
}

const goBack = () => {
  window.close()
}

const publish = async () => {
  // 这里可以添加发布逻辑
  if (confirm('确定要发布这篇文章吗？')) {
    // 发送发布请求
    window.opener.postMessage({ action: 'publish', postId: post.value.id }, '*')
    window.close()
  }
}

onMounted(() => {
  // 从localStorage获取预览数据
  const previewData = localStorage.getItem('post_preview')
  if (previewData) {
    try {
      const data = JSON.parse(previewData)
      post.value = data

      // 清理localStorage
      localStorage.removeItem('post_preview')
    } catch (error) {
      console.error('解析预览数据失败:', error)
    }
  }

  // 加载分类数据（如果需要）
  // 这里可以从props或API获取
  categories.value = page.props.categories || []

  // 监听来自父窗口的消息
  window.addEventListener('message', (event) => {
    if (event.data.action === 'updatePreview') {
      post.value = event.data.post
    }
  })
})
</script>

<style scoped>
.prose {
  color: #1a202c;
}
.prose h1 { @apply text-3xl font-bold mt-8 mb-4; }
.prose h2 { @apply text-2xl font-bold mt-6 mb-3; }
.prose h3 { @apply text-xl font-bold mt-4 mb-2; }
.prose p { @apply my-4; }
.prose ul { @apply list-disc list-inside my-4; }
.prose ol { @apply list-decimal list-inside my-4; }
.prose blockquote { @apply border-l-4 border-gray-300 pl-4 my-4 italic; }
.prose pre { @apply bg-gray-100 p-4 rounded-lg my-4 overflow-x-auto; }
.prose code { @apply bg-gray-100 px-2 py-1 rounded text-sm; }
.prose img { @apply rounded-lg my-6; }
.prose a { @apply text-blue-600 hover:text-blue-800 underline; }
</style>